package spark.graphics;

import spark.exception.LoadingException;
import spark.graphics.scenegraph.*;
import spark.math.Vector2;
import spark.math.Vector3;

import java.util.HashMap;

public class Font {
	private static final String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:,;~`!@#$%^&+-*/()_='{}[]?<>|\\\" ";
	private HashMap<Character, ISpriteRenderable> characters = new HashMap<Character, ISpriteRenderable>();

	public static Font makeFont(String fontSpriteMapPath, String themePath) throws LoadingException {
		return Font.makeFont(fontSpriteMapPath, "default", themePath);
	}

	public static Font makeFont(String fontSpriteMapPath, String theme, String themePath) throws LoadingException {
		Font font = new Font();
		ISpriteMap spriteMap = new SpriteMap(fontSpriteMapPath, "default", themePath);

		for(int i = 0; i < alphabet.length(); i++) {
			Sprite sprite = null;
			Character character = alphabet.charAt(i);
			try {
				sprite = spriteMap.getSprite(Character.toString(character));
			}
			catch(SpriteMap.SpriteLoadFailedException e) {
				throw new LoadingException("Character '" + character + "' missing from sprite map", e);
			}
			SpriteRenderable spriteRenderable = new SpriteRenderable();
			spriteRenderable.setSprite(sprite);
			//todo : improv
			spriteRenderable.setDimensions(new Vector2(0.4f, 0.5f));
			font.characters.put(character, spriteRenderable);
		}

		return font;
	}

	public SceneGraphNode getText(String text) {
		SceneGraphNode root = new RootNode();
		float shift = 0;
		for(int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			TranslationNode translation = new TranslationNode(new Vector2(shift, 0));
			ISpriteRenderable spriteRenderable = characters.get(c);
			translation.addChild(new SpriteNode().registerForRendering(spriteRenderable));
			shift += spriteRenderable.getDimensions().x;
			root.addChild(translation);
		}
		return root;
	}

	public void release() {
		for(ISpriteRenderable iSpriteRenderable : characters.values()) {
			iSpriteRenderable.getSprite().release();
		}
	}
}
